package com.yjht.online.generate.impl.sysparam.plat;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.yjht.online.generate.model.sysparam.SysParam;
import com.yjht.online.generate.sysparam.SysParamGenerateProssor;
import com.yjht.online.util.OnLineFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;


public abstract class GenerateSysParamByMould implements SysParamGenerateProssor {
    final static Logger logger = LoggerFactory.getLogger(GenerateSysParamByMould.class);

    @Override
    public void generateSysParam(SysParam sysParam) {
        Field[] fields = ReflectUtil.getFields(SysParam.class);

        Arrays.stream(fields)
                .filter(f -> ReflectUtil.getFieldValue(sysParam, f) == null)
                .forEach(field -> ReflectUtil.setFieldValue(sysParam, field, ""));

        logger.info("生成系统参数表sql");
        String rootPath = OnLineFileUtil.getRuningFilePath("templates");
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig(rootPath, TemplateConfig.ResourceMode.FILE));
        String fileName = templateFile();
        Template template = engine.getTemplate(fileName);

        String result = template.render(BeanUtil.beanToMap(sysParam));

        String path = getOutPutPath() + StrUtil.SLASH + getFileName();

        File file = OnLineFileUtil.getOutPutFile(path);
        FileUtil.del(file);
        FileUtil.touch(file);
        FileUtil.writeBytes(result.getBytes(), file);

        logger.info("生成系统参数表sql结束");
    }

    protected abstract String templateFile();

    protected abstract String getOutPutPath();

    protected abstract String getFileName();
}
